package com.enqualcomm.kids.activities;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.BuildConfig;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.component.DownloadAppIntentService;
import com.enqualcomm.kids.config.StateCode;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.GetNewAppParams;
import com.enqualcomm.kids.network.socket.response.GetNewAppResult;
import com.enqualcomm.kids.view.LazyViewPager;
import com.enqualcomm.kids.view.MyViewPager;
import com.enqualcomm.kids.view.dialog.MyUpdateCommitDialog;
import com.iflytek.thridparty.G;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import common.utils.DensityUtil;
import common.utils.MyLogger;
import common.utils.PlatformUtil;
import common.utils.PromptUtil;
import rx.functions.Action1;

@EActivity(R.layout.activity_guide)
public class GuideActivity extends BaseActivity {

    private int resIds[] = new int[]{
            R.drawable.guide1,
            R.drawable.guide2,
            R.drawable.guide3,
/*
            R.drawable.guide4
*/
    };
    private int previousPointPosition; // 前一个被选中的点的索引
    private boolean showProtocol;
    private List<ImageView> images = new ArrayList<ImageView>();


    @ViewById(R.id.guide_over_btn)
    View guide_over_btn;
    @ViewById(R.id.qhyd_over_btn)
    View qhyd_over_btn;
    @ViewById(R.id.guide_point_group)
    LinearLayout guide_point_group;
    @ViewById(R.id.agreement_ll)
    View agreement_ll;
    @ViewById(R.id.agreement_cb)
    CheckBox agreement_cb;
    @ViewById(R.id.viewpager)
    MyViewPager pager;
    @ViewById(R.id.agreement_tv)
    TextView agreement_tv;
    NetworkModel networkModel;
    @ViewById(R.id.root)
    FrameLayout root;

    @ViewById(R.id.guide_webview)
    WebView guide_webview;


    @Click({R.id.agreement_tv, R.id.guide_over_btn, R.id.qhyd_over_btn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.agreement_tv:
                showAgreement();
                break;
            case R.id.guide_over_btn:
                if (!agreement_cb.isChecked()) {
                    //没有选中
                    PromptUtil.toast(getApplicationContext(), R.string.choose_agreement);
                    return;
                }

                startActivity(LoginActivity.class);
//                startActivity(ChooseLoginActivity_.class);
//                if ("品冠达-平安星智能".equals(BuildConfig.CHANNEL)) {
//                    startActivity(LoginActivity.class);
//                } else {
//                    startActivity(ChooseLoginActivity_.class);
//                }
                finish();
                break;
            case R.id.qhyd_over_btn:
                startActivity(LoginActivity.class);
//                startActivity(ChooseLoginActivity_.class);
//                if ("品冠达-平安星智能".equals(BuildConfig.CHANNEL)) {
//                    startActivity(LoginActivity.class);
//                } else {
//                    startActivity(ChooseLoginActivity_.class);
//                }
                finish();
                break;
        }
    }

    @AfterViews
    void setupViews() {

        if ("前海毅德-儿童天使".equals(BuildConfig.CHANNEL)) {
            resIds = new int[]{
                    R.drawable.guide1,
                    R.drawable.guide2,
                    R.drawable.guide3,
                    R.drawable.guide4

            };
        } else {
            resIds = new int[]{
                    R.drawable.guide1,
                    R.drawable.guide2,
                    R.drawable.guide3,
//            R.drawable.guide4

            };
        }
        checkPermission();
        if ("中性长连接-在哪儿".equals(BuildConfig.CHANNEL) || "奇新智能_儿童卫士".equals(BuildConfig.CHANNEL)
                || "陆陆通_激光鸟".equals(BuildConfig.CHANNEL) || "中性-手表".equals(BuildConfig.CHANNEL)) {

        } else {
            //标准版本
            showProtocol = true;
            agreement_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        }

        //初始化小点
        //初始化图片
        ImageView iv = null;
        View point = null;
        LinearLayout.LayoutParams params;
        int width = DensityUtil.dip2px(this, 12);
        int height = DensityUtil.dip2px(this, 16);
        int margin = DensityUtil.dip2px(this, 8);
        for (int i = 0; i < resIds.length; i++) {
            iv = new ImageView(this);
            iv.setBackgroundResource(resIds[i]);
            images.add(iv);

            point = new View(this);
            params = new LinearLayout.LayoutParams(width, height);
            params.leftMargin = margin;
            point.setLayoutParams(params);
            point.setBackgroundResource(R.drawable.selector_guide_point_bg);
            point.setEnabled(false); // 把点置为没选中的状态
            guide_point_group.addView(point);
        }
        pager.setAdapter(new PagerAdapter() {
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(images.get(position));
                return images.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                container.removeView(images.get(position));
            }

            @Override
            public int getCount() {
                return images.size();
            }
        });

        pager.setOnPageChangeListener(new LazyViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (position == images.size() - 1) {
                    //如果是最后一张
                    if ("前海毅德-儿童天使".equals(BuildConfig.CHANNEL)) {
                        qhyd_over_btn.setVisibility(View.VISIBLE);
                    } else {
                        guide_over_btn.setVisibility(View.VISIBLE);

                        if (showProtocol) {
                            agreement_ll.setVisibility(View.VISIBLE);
                        }
                    }

                } else {
                    if ("前海毅德-儿童天使".equals(BuildConfig.CHANNEL)) {
                        if (qhyd_over_btn.getVisibility() == View.VISIBLE) {
                            qhyd_over_btn.setVisibility(View.GONE);
                        }
                    } else {
                        if (guide_over_btn.getVisibility() == View.VISIBLE) {
                            guide_over_btn.setVisibility(View.GONE);
                        }
                        if (agreement_ll.getVisibility() == View.VISIBLE) {
                            agreement_ll.setVisibility(View.GONE);
                        }
                    }
                }

                guide_point_group.getChildAt(previousPointPosition).setEnabled(false); // 把前一个点置为未选中
                guide_point_group.getChildAt(position).setEnabled(true);// 把当前的点置为选中

                previousPointPosition = position; // 把当前的点用前一个点的变量记录下来
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        guide_point_group.getChildAt(0).setEnabled(true); // 把第0个点选中
//        WebSettings webSettings = guide_webview.getSettings();
//        webSettings.setJavaScriptEnabled(true);
//        webSettings.setDefaultTextEncodingName("UTF-8");
//        guide_webview.addJavascriptInterface(new CallJava(), "CallJava");
//        guide_webview.loadUrl("file:///android_asset/guide/show.html");

        guide_webview.setVisibility(View.GONE);
        /**jianc检测更新*/
        networkModel = new NetworkModel();
        checkForUpdate();
    }

    private void checkForUpdate() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            networkModel.loadDataFromServer(new SocketRequest<GetNewAppResult>(new GetNewAppParams(1, String.valueOf(BuildConfig.VERSION_CODE), BuildConfig.CHANNEL),
                    new NetworkListener<GetNewAppResult>() {
                        @Override
                        public void onError(VolleyError error) {
                        }

                        @Override
                        public void onSuccess(GetNewAppResult response) {
                            if (response.code == StateCode.OK && response.result.url != null) {
                                showCommitDialog(response);
                            }
                        }
                    }));
        }
    }

    private void showCommitDialog(final GetNewAppResult appInfo) {
        MyUpdateCommitDialog dialog = new MyUpdateCommitDialog(this, appInfo, new MyUpdateCommitDialog.UpdateCommitDialogCallBack() {

            @Override
            public void onCommit() {
                // 后台下载升级
                Intent service = new Intent(getApplicationContext(), DownloadAppIntentService.class);
                service.putExtra("url", appInfo.result.url);
                startService(service);
            }

            @Override
            public void onCancel() {
            }
        });
        dialog.show();
    }

    private void showAgreement() {
        View contentView = getLayoutInflater().inflate(R.layout.popwindow_agreement, null);
        WebView agreement_webview = (WebView) contentView.findViewById(R.id.agreement_webview);
//        if ("畅宇国际-熊卫士守护者".equals(BuildConfig.CHANNEL)) {
        if (Locale.SIMPLIFIED_CHINESE.equals(getResources().getConfiguration().locale)) {
            agreement_webview.loadUrl("file:///android_asset/agreement.html");
        } else if ("zh".equals(getResources().getConfiguration().locale.getLanguage())) {
            agreement_webview.loadUrl("file:///android_asset/agreement_tradition.html");
        } else {
            agreement_webview.loadUrl("file:///android_asset/agreement_english.html");
        }
//        } else {
//            if (Locale.SIMPLIFIED_CHINESE.equals(getResources().getConfiguration().locale)) {
//                agreement_webview.loadUrl("file:///android_asset/agreement.html");
//            } else {
//                agreement_webview.loadUrl("file:///android_asset/agreement_english.html");
//            }
//        }

        PopupWindow mPopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.showAtLocation(root, Gravity.CENTER, 0, 0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        networkModel.onStop();
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        RxPermissions.getInstance(this)
                .request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                )
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                    }
                });
    }

    //    js调用java函数


    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    class CallJava {
        @JavascriptInterface
        public String getAgreementUrl() {
            MyLogger.kLog().i("==============js调取获取安装徐可意协议");
            String path = "ceshi";
            InputStream abpath = getClass().getResourceAsStream("file:///android_asset/agreement.html");
            try {
                path = new String(InputStreamToByte(abpath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            MyLogger.kLog().i("path==============" + path);
            return path;
        }

        @JavascriptInterface
        public void finishGuide() {
            MyLogger.kLog().i("==============js跳转到登录界面");
//            GuideActivity.this.startActivity(ChooseLoginActivity_.class);
            GuideActivity.this.startActivity(LoginActivity.class);
            GuideActivity.this.finish();
        }

    }
}
